package com.shuoyue.ycgk.ui.main.main_flowable;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.cardview.widget.CardView;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.shuoyue.ycgk.R;
import com.shuoyue.ycgk.apputis.GlideImageLoader;
import com.shuoyue.ycgk.base.BaseMvpFragment;
import com.shuoyue.ycgk.entity.Course;
import com.shuoyue.ycgk.entity.Mok;
import com.shuoyue.ycgk.entity.MyBanner;
import com.shuoyue.ycgk.entity.PaperSet;
import com.shuoyue.ycgk.entity.SpecialType;
import com.shuoyue.ycgk.entity.Type;
import com.shuoyue.ycgk.entity.UserTestPaper;
import com.shuoyue.ycgk.ui.course.CourseTypeActivity;
import com.shuoyue.ycgk.ui.course.SpecialCourseActivity;
import com.shuoyue.ycgk.ui.course.info.CourseInfoActivity;
import com.shuoyue.ycgk.ui.estimate.EstimateScoreActivity;
import com.shuoyue.ycgk.ui.main.adapter.HomeButton;
import com.shuoyue.ycgk.ui.main.adapter.HomeButtonsAdapter;
import com.shuoyue.ycgk.ui.main.adapter.HomeCourseAdapter;
import com.shuoyue.ycgk.ui.main.adapter.HomeMokRecAdapter;
import com.shuoyue.ycgk.ui.main.adapter.QuestionBanGroupAdapter;
import com.shuoyue.ycgk.ui.main.contract.FragmentMainItemContract;
import com.shuoyue.ycgk.ui.mine.info.ShareGiftActivity2;
import com.shuoyue.ycgk.ui.mok.MokDetailActivity;
import com.shuoyue.ycgk.ui.mok.MokListActivity;
import com.shuoyue.ycgk.ui.news.NewsInfoActivity;
import com.shuoyue.ycgk.ui.papergroups.SpecialQuestionContract;
import com.shuoyue.ycgk.ui.papergroups.freedomnew.FreedomGroupInfoActivity;
import com.shuoyue.ycgk.ui.papergroups.groupcommon.PaperCommonInfoActivity;
import com.shuoyue.ycgk.ui.papergroups.groupcommon.PaperGroupCommonActivity;
import com.shuoyue.ycgk.ui.papergroups.hotquestion.HotQuestionActivity;
import com.shuoyue.ycgk.ui.papergroups.running.RunningInfoActivity;
import com.shuoyue.ycgk.ui.papergroups.special.SpecialAdapter;
import com.shuoyue.ycgk.ui.papergroups.special.SpecialListActivity;
import com.shuoyue.ycgk.ui.questionbank.practice.specialtraining.questionitem.SpeciaDoingActivity;
import com.shuoyue.ycgk.ui.recruitment.newsinfo.RecurimentInfoActivity;
import com.shuoyue.ycgk.ui.shop.ShopInfoActivity;
import com.shuoyue.ycgk.ui.shop.ShopTabActivity;
import com.shuoyue.ycgk.utils.GridSpacingItemDecoration;
import com.shuoyue.ycgk.utils.HorizontalSpacesItemDecoration;
import com.shuoyue.ycgk.utils.SizeUtil;
import com.shuoyue.ycgk.utils.SpacesItemDecoration;
import com.shuoyue.ycgk.views.PageIndicator;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 首页数据片段
 */
public class FragmentMainItem extends BaseMvpFragment<FragmentMainItemContract.Presenter>
        implements FragmentMainItemContract.View, SpecialQuestionContract.View {

    @BindView(R.id.home_banner)
    Banner homeBanner;
    @BindView(R.id.pageindicatorBanner)
    PageIndicator pageindicatorBanner;
    //    @BindView(R.id.buttons)
//    RecyclerView buttonsRecycleView;
    @BindView(R.id.specialMore)
    TextView specialMore;
    @BindView(R.id.SpecialRecycleView)
    RecyclerView specialRecycleView;
    @BindView(R.id.lay_special)
    CardView laySpecial;
    @BindView(R.id.mokMore)
    TextView mokMore;
    @BindView(R.id.lay_mok)
    CardView layMok;
    @BindView(R.id.bankMore)
    TextView bankMore;
    @BindView(R.id.questionBankRecycle)
    RecyclerView questionBankRecycle;
    @BindView(R.id.lay_questionBank)
    CardView layQuestionBank;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.recycleMok)
    RecyclerView recycleMok;
    @BindView(R.id.courseRecycleView)
    RecyclerView courseRecycleView;
    @BindView(R.id.lay_course)
    CardView layCourse;
    @BindView(R.id.lay_banner)
    CardView layBanner;
    @BindView(R.id.buttonsPager)
    ViewPager buttonsPager;
    @BindView(R.id.pageindicatorButtons)
    PageIndicator pageindicatorButtons;

    Type baseType;
    Type topType;
    public String title;

    boolean isScrollAtTop = true;
    ArrayList<MyBanner> banners;

    SpecialQuestionContract.Presenter spePresenter;


    HomeMokRecAdapter homeMokRecAdapter;
    SpecialAdapter specialAdapter;
    HomeCourseAdapter homeCourseAdapter;
    QuestionBanGroupAdapter questionBanGroupAdapter;


    @Override
    public void initParams(Bundle bundle) {
        topType = (Type) bundle.getSerializable("questionType");
        baseType = (Type) bundle.getSerializable("baseType");
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_main_home_item;
    }

    @Override
    protected void initView() {
        LinearLayoutManager layoutManageeMok = new LinearLayoutManager(mContext);
        layoutManageeMok.setOrientation(LinearLayoutManager.HORIZONTAL);
        recycleMok.setLayoutManager(layoutManageeMok);
        specialRecycleView.setLayoutManager(new LinearLayoutManager(mContext));
        questionBankRecycle.setLayoutManager(new LinearLayoutManager(mContext));
        specialRecycleView.addItemDecoration(new SpacesItemDecoration(SizeUtil.dip2px(mContext, 8), true));
        questionBankRecycle.addItemDecoration(new SpacesItemDecoration(SizeUtil.dip2px(mContext, 8), true));
        recycleMok.addItemDecoration(new HorizontalSpacesItemDecoration(SizeUtil.dip2px(mContext, 8), true));
        courseRecycleView.setLayoutManager(new GridLayoutManager(mContext, 2));
        courseRecycleView.addItemDecoration(new GridSpacingItemDecoration(2, SizeUtil.dip2px(mContext, 8), false));
//        buttonsRecycleView.setLayoutManager(new GridLayoutManager(mContext, 4));
//        buttonsRecycleView.addItemDecoration(new GridSpacingItemDecoration(4, SizeUtil.dip2px(mContext, 16), false));
        scrollView.setOnScrollChangeListener((NestedScrollView.OnScrollChangeListener) (v, scrollX, scrollY, oldScrollX, oldScrollY) -> {
            isScrollAtTop = scrollY == 0;
        });
        initAdapter();

    }

    void initAdapter() {
        //模考
        homeMokRecAdapter = new HomeMokRecAdapter(null);
        recycleMok.setAdapter(homeMokRecAdapter);
        homeMokRecAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            Mok mok = (Mok) adapter.getItem(position);
            MokDetailActivity.start(mContext, mok.getId());
        });
        //专项
        /**
         * 专项适配器点击监听
         */
        BaseQuickAdapter.OnItemChildClickListener specialLis = (adapter, view, position) -> {
            SpecialType specialType = (SpecialType) adapter.getItem(position);
            int modelId = topType.getId();

            if (modelId == 47 || modelId == 58) {
                spePresenter.createSpecialPager(specialType.getName(),
                        specialType.getSectionId(),
                        0,
                        0);
            } else {
                spePresenter.createSpecialPager(specialType.getName(),
                        specialType.getChapterId(),
                        specialType.getSectionId(),
                        specialType.getEpId());
            }

        };
        specialAdapter = new SpecialAdapter(null, specialLis);
        specialAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            SpecialType specialType = (SpecialType) adapter.getItem(position);
            int modelId = topType.getId();
            switch (view.getId()) {
                case R.id.lay_all:
                case R.id.start:
                    if (modelId == 47 || modelId == 58) {
                        specialType.setSelect(!specialType.isSelect());
                        adapter.notifyDataSetChanged();
                    } else {
                        spePresenter.createSpecialPager(specialType.getName(),
                                specialType.getChapterId(),
                                specialType.getSectionId(),
                                specialType.getEpId());
                    }
                    break;
                case R.id.indicator:
                    specialType.setSelect(!specialType.isSelect());
                    adapter.notifyDataSetChanged();
                    break;
            }
        });
        specialRecycleView.setAdapter(specialAdapter);
        //题
        homeCourseAdapter = new HomeCourseAdapter(null);
        homeCourseAdapter.setOnItemChildClickListener((adapter1, view, position) -> {
            Course course = (Course) adapter1.getItem(position);
            startActivity(new Intent(mContext, CourseInfoActivity.class)
                    .putExtra("id", course.getId()));
        });
        courseRecycleView.setAdapter(homeCourseAdapter);

        questionBanGroupAdapter = new QuestionBanGroupAdapter(null);
        questionBankRecycle.setAdapter(questionBanGroupAdapter);
        questionBanGroupAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            PaperSet paperSet = (PaperSet) adapter.getItem(position);
            PaperCommonInfoActivity.start(mActivity, paperSet.getId(), -1,baseType.getSubjectTypeId());

        });
    }

    public static FragmentMainItem getInstance(Type topType, Type baseType) {
        FragmentMainItem fragment = new FragmentMainItem();
        fragment.title = topType.getName();
        Bundle bundle = new Bundle();
        bundle.putSerializable("questionType", topType);
        bundle.putSerializable("baseType", baseType);

        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected void initData() {
        spePresenter = new SpecialQuestionContract.Presenter();
        spePresenter.attachView(this);
        mPresenter = new FragmentMainItemContract.Presenter();
        mPresenter.attachView(this);

        mPresenter.getBanners(topType.getId());
        mPresenter.getBestCourse(baseType.getName());
        mPresenter.getSpecial(topType.getId(), null);// topType.getSubjectId());
        mPresenter.getMok(topType.getId());
//        mPresenter.getPaperSet(topType.getSubjectId());
        mPresenter.getPaperSet(topType.getId());
        setButtons();
    }

    @Override
    public String getTitle() {
        return title;
    }

    @OnClick({R.id.specialMore, R.id.mokMore, R.id.bankMore, R.id.courseMore})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.specialMore:
                startActivity(new Intent(mContext, SpecialListActivity.class)
                        .putExtra("moduleId", topType.getId())
                        .putExtra("subjectId", topType.getSubjectId()));
                break;
            case R.id.mokMore:
//                MokTypeActivity.start(mActivity);
                MokListActivity.start(mActivity, baseType.getSubjectTypeId());
                break;
            case R.id.bankMore:
                PaperGroupCommonActivity.start(mActivity, -1, topType.getId(), false);

//                startActivity(new Intent(mContext, PaperSetActivity.class));
                break;
            case R.id.courseMore:
                startActivity(new Intent(mContext, CourseTypeActivity.class));
                break;
        }
    }

    /**
     * 设置banner信息
     *
     * @param data
     */
    public void setmBannerView(ArrayList<MyBanner> data) {
        layBanner.setVisibility(data == null || data.size() == 0 ? View.GONE : View.VISIBLE);
        List<String> iBanners = new ArrayList<>();
        for (MyBanner banner : data) {
            iBanners.add(banner.getImgUrl());
        }
        //设置banner样式
        homeBanner.setBannerStyle(BannerConfig.NOT_INDICATOR)
                //设置图片加载器
                .setImageLoader(new GlideImageLoader())
                //设置图片集合
                .setImages(iBanners)
                //设置banner动画效果
                .setBannerAnimation(Transformer.Default)
//            //设置标题集合（当banner样式有显示title时）
                .setBannerTitles(iBanners)
                //设置自动轮播，默认为true
                .isAutoPlay(true)
                //设置轮播时间
                .setDelayTime(3000)
                //设置指示器位置（当banner模式中有指示器时）
                .setIndicatorGravity(BannerConfig.CENTER)

                .setOnBannerListener(position -> {
                    MyBanner myBanner = banners.get(position);
//1，课程，2图书，3习题包，4公告，5资讯，6模考，7估分，8考前冲刺
                    switch (myBanner.getProductType()) {
                        case 1:
                            startActivity(new Intent(mContext, CourseInfoActivity.class)
                                    .putExtra("id", myBanner.getProductId()));
                            break;
                        case 2:
                            startActivity(new Intent(mContext, ShopInfoActivity.class)
                                    .putExtra("id", myBanner.getProductId()));
                            break;
                        case 3:
                            PaperCommonInfoActivity.start(mActivity, myBanner.getProductId(), 1,baseType.getSubjectTypeId());

                            break;
                        case 4:
                            startActivity(new Intent(mContext, RecurimentInfoActivity.class)
                                    .putExtra("id", myBanner.getProductId()));
                            break;
                        case 5:
                            startActivity(new Intent(mContext, NewsInfoActivity.class)
                                    .putExtra("id", myBanner.getProductId()));
                            break;
                        case 6:
                            startActivity(new Intent(mContext, MokDetailActivity.class)
                                    .putExtra("id", myBanner.getProductId()));
                            break;
                        case 7:
                            startActivity(new Intent(mContext, EstimateScoreActivity.class)
                                    .putExtra("id", baseType.getId()));
                            break;
                    }
                })
                //banner设置方法全部调用完毕时最后调用
                .start();
//            homeBanner.setBannerView(iBanners).setImageCorner(18).start();
        homeBanner.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                if (pageindicatorBanner != null)
                    pageindicatorBanner.setCurrentPage(position);

            }
        });
        pageindicatorBanner.setNumPages(iBanners.size());
        pageindicatorBanner.setCurrentPage(0);

    }


    private void setButtons() {
        List<HomeButton> homeButtons = new ArrayList<>();
        homeButtons.add(getHomeButton("考上也全退", R.mipmap.home_bt_smkc, 0));
        homeButtons.add(getHomeButton("课程购买", R.mipmap.home_bt_course, 1));
        homeButtons.add(getHomeButton("图书商城", R.mipmap.home_bt_books, 2));
        homeButtons.add(getHomeButton("时政热点", R.mipmap.home_bt_news, 3));
        homeButtons.add(getHomeButton("考试估分", R.mipmap.estimeate, 9));
        homeButtons.add(getHomeButton("历年真题", R.mipmap.home_bt_pagers, 4));
        homeButtons.add(getHomeButton("在线模考", R.mipmap.home_bt_mok, 6));
        homeButtons.add(getHomeButton("分享有礼", R.mipmap.home_bt_share, 7));
        homeButtons.add(getHomeButton("考前冲刺", R.mipmap.home_item_rush, 8));
        homeButtons.add(getHomeButton("自由组卷", R.mipmap.home_bt_special_free, 5));


        LayoutInflater inflater = LayoutInflater.from(mContext);
        int pageCount = (int) Math.ceil(homeButtons.size() * 1.0 / 8);
        List<View> viewList = new ArrayList<View>();
        for (int index = 0; index < pageCount; index++) {
            //每个页面都是inflate出一个新实例
            RecyclerView recyclerView = (RecyclerView) inflater.inflate(R.layout.item_simple_recycleview, buttonsPager, false);
            recyclerView.setLayoutManager(new GridLayoutManager(mContext, 4));
//            recyclerView.addItemDecoration(new GridSpacingItemDecoration(4, SizeUtil.dip2px(mContext, 16), false));
            List<HomeButton> homeButtonsPage = new ArrayList<>();
            for (int i = index * 8; i < homeButtons.size() && i < (index + 1) * 8; i++) {
                homeButtonsPage.add(homeButtons.get(i));
            }
            HomeButtonsAdapter homeButtonsAdapter = new HomeButtonsAdapter(homeButtonsPage);
            recyclerView.setAdapter(homeButtonsAdapter);
            homeButtonsAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                HomeButton homeButton = homeButtonsAdapter.getItem(position);
                switch (homeButton.getAction()) {
                    case 0:
                        startActivity(new Intent(mContext, SpecialCourseActivity.class));
                        break;
                    case 1:
                        //跳转课程
                        startActivity(new Intent(mContext, CourseTypeActivity.class));
                        break;
                    case 2:
                        //商城
                        startActivity(new Intent(mContext, ShopTabActivity.class));
                        break;
                    case 3:
                        //跳转资讯
//                        ((MainTabActivity) Objects.requireNonNull(getActivity())).goIndexpage(3);
//                        PaperGroupCommonActivity.start(mActivity, 2, false);
                        HotQuestionActivity.start(mActivity, baseType);

                        break;
                    case 4:
                        PaperGroupCommonActivity.start(mActivity, 1, topType.getId(), false);
                        break;
                    case 5:
//                    PaperGroupCommonActivity.start(mActivity, 3, false);
                        FreedomGroupInfoActivity.start(mActivity, topType.getId());
                        break;
                    case 6:
//                        MokTypeActivity.start(mActivity);
                        MokListActivity.start(mActivity, baseType.getSubjectTypeId());
                        break;
                    case 7:
                        startActivity(new Intent(mContext, ShareGiftActivity2.class));
                        break;
                    case 8:
//                        PaperGroupCommonActivity.start(mActivity, 2, true);
                        RunningInfoActivity.start(mContext, topType.getId(), baseType.getSubjectTypeId());
                        break;
                    case 9:
//                        PaperGroupCommonActivity.start(mActivity, 2, true);
                        EstimateScoreActivity.start(mContext, baseType.getId());
                        break;
                }
            });
            viewList.add(recyclerView);
        }
        CagegoryViewPagerAdapter adapter = new CagegoryViewPagerAdapter(viewList);
        buttonsPager.setAdapter(adapter);
        pageindicatorButtons.setNumPages(pageCount);
        pageindicatorButtons.setCurrentPage(0);
        buttonsPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                pageindicatorButtons.setCurrentPage(position);
            }
        });


    }

    HomeButton getHomeButton(String title, int src, int action) {
        HomeButton homeButton = new HomeButton();
        homeButton.setTitle(title);
        homeButton.setSrc(src);
        homeButton.setAction(action);
        return homeButton;
    }

    @Override
    public void setBanners(ArrayList<MyBanner> banners) {
        this.banners = banners;
        setmBannerView(banners);
    }

    @Override
    public void setCourse(ArrayList<Course> data) {
        layCourse.setVisibility(data == null || data.size() == 0 ? View.GONE : View.VISIBLE);
        homeCourseAdapter.resetData(data);
    }

    /**
     * 设置专项适配器
     *
     * @param data
     */
    @Override
    public void setSpecialList(ArrayList<SpecialType> data) {
        try {
            packSpeciaType(data);
            laySpecial.setVisibility(data == null || data.size() == 0 ? View.GONE : View.VISIBLE);
            specialMore.setVisibility(data == null || data.size() < 7 ? View.GONE : View.VISIBLE);
            specialAdapter.resetData(data.size() > 7 ? data.subList(0, 7) : data);
        } catch (Exception e) {
            Log.e("error", e.getMessage());
        }

    }

    void packSpeciaType(ArrayList<SpecialType> data) {
        for (SpecialType specialTypeC : data) {
            specialTypeC.setChapterId(specialTypeC.getId());
            if (specialTypeC.getChildren() != null)
                for (SpecialType specialTypes : specialTypeC.getChildren()) {
                    specialTypes.setChapterId(specialTypeC.getId());
                    specialTypes.setSectionId(specialTypes.getId());
                    if (specialTypes.getChildren() != null)
                        for (SpecialType specialTypee : specialTypes.getChildren()) {
                            specialTypee.setChapterId(specialTypeC.getId());
                            specialTypee.setSectionId(specialTypes.getId());
                            specialTypee.setEpId(specialTypee.getId());

                        }
                }
        }
    }


    @Override
    public void setMokList(ArrayList<Mok> data) {
        layMok.setVisibility(data == null || data.size() == 0 ? View.GONE : View.VISIBLE);
        homeMokRecAdapter.resetData(data);
    }

    @Override
    public void setPaperSet(List<PaperSet> data) {
        layQuestionBank.setVisibility(data == null || data.size() == 0 ? View.GONE : View.VISIBLE);
        questionBanGroupAdapter.resetData(data);
    }


    public void refresh() {
        mPresenter.getBestCourse(baseType.getName());
        mPresenter.getBanners(topType.getId());
        mPresenter.getSpecial(topType.getId(), topType.getSubjectId());
        mPresenter.getMok(topType.getId());
//        mPresenter.getPaperSet(topType.getSubjectId());
//        mPresenter.getMok(topType.getId());
        mPresenter.getPaperSet(topType.getId());
        buttonsPager.setCurrentItem(0);
    }


    @Override
    public void setTypeList(List<SpecialType> specialTypeList) {

    }

    @Override
    public void setPagerInfo(String name, UserTestPaper specialPager) {
        SpeciaDoingActivity.start(mContext, specialPager, name,
                null);

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onResume() {
        super.onResume();
        new Handler().postDelayed(() -> mPresenter.getSpecial(topType.getId(), topType.getSubjectId()), 7000);
    }
}
